<template>
  <div class="following_exchange">
    <searchBox>
      <template #yyxbread>
        <div style="display: flex; align-items: center">
          <el-icon>
            <Location />
          </el-icon>
          <span class="f12 ml10 mr10">当前位置：</span>
          <el-breadcrumb separator="/" class="f14">
            <el-breadcrumb-item>预算报价</el-breadcrumb-item>
            <el-breadcrumb-item class="active">预算退换货单</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </template>
    </searchBox>
    <div class="exchange_content">
      <div class="content_box">
        <div class="box_top">
          <el-radio-group class="top_radio" v-model="orderType" @change="getOrderDetail">
            <el-radio-button class="radio_btn" label="退货单" value="1" />
            <el-radio-button class="radio_btn" label="换货单" value="2" />
          </el-radio-group>
          <el-button class="top_btn" @click="goBack()"> 返回上一页 </el-button>
        </div>
        <div id="tableBox" class="box_content" v-loading="loading">
          <div class="content_table">
            <div class="table_title mb20">
              <span class="title_text" v-if="isRefund"> 退货单 </span>
              <span class="title_text" v-else> 换补单 </span>
              <span class="title_info">
                （费用合计：
                <span class="info_price"> ¥{{ detailInfo.refundBudgetTotlalMoney || detailInfo.budgetTotlalMoney }} </span>
                -
                <span class="info_price">{{ detailInfo.refundBudgetTotlalCNMoney || detailInfo.budgetTotlalCNMoney }}</span>
                <span> ，管理费：¥{{ detailInfo.refundManagerFee || detailInfo.managerFee }} </span>
                <span> ，税金费：¥{{ detailInfo.refundTaxesFee || detailInfo.taxesFee }} </span>
                <span> ，综合项：¥{{ detailInfo.refundCustomComprehensiveFee || detailInfo.customComprehensiveFee }} </span>
                <span> +其他费用：¥{{ detailInfo.refundOtherFee || detailInfo.otherFee }}） </span>
              </span>
            </div>
            <div class="table_input mb20">
              <div class="input_box">
                <span>管理费</span>
                <el-input
                  v-if="isRefund"
                  v-model="detailInfo.refundManagerFee"
                  placeholder="请输入"
                  @input="handleInput($event, 'refundManagerFee')"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
                <el-input
                  v-else
                  v-model="detailInfo.managerFee"
                  placeholder="请输入"
                  @input="handleInput($event, 'managerFee')"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
              </div>
              <div class="input_box">
                <span>税金费</span>
                <el-input
                  v-if="isRefund"
                  v-model="detailInfo.refundTaxesFee"
                  placeholder="请输入"
                  @input="handleInput($event, 'refundTaxesFee')"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
                <el-input
                  v-else
                  v-model="detailInfo.taxesFee"
                  placeholder="请输入"
                  @input="handleInput($event, 'taxesFee')"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
              </div>
              <div class="input_box">
                <span>其他费用</span>
                <el-input
                  v-if="isRefund"
                  v-model="detailInfo.refundOtherFee"
                  placeholder="请输入"
                  @input="handleInput($event, 'refundOtherFee')"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
                <el-input
                  v-else
                  v-model="detailInfo.otherFee"
                  placeholder="请输入"
                  @input="handleInput($event, 'otherFee')"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
              </div>
              <div v-if="!isRefund && detailInfo.regularViewStatus" class="input_box">
                <span>正价商品</span>
                <el-input
                  v-model="detailInfo.customerRegularDiscount"
                  oninput="value=value.replace(/^0(0+|\d+)|[^\d]+/g,'')"
                  placeholder="请输入"
                  @input="handleInput($event, 'customerRegularDiscount')"
                  @change="updateOrderHandle()"
                >
                  <template #suffix>%</template>
                </el-input>
              </div>
              <div v-if="!isRefund && detailInfo.specialViewStatus" class="input_box">
                <span>特价商品</span>
                <el-input
                  v-model="detailInfo.customerSpecialDiscount"
                  oninput="value=value.replace(/^0(0+|\d+)|[^\d]+/g,'')"
                  placeholder="请输入"
                  @input="handleInput($event, 'customerSpecialDiscount')"
                  @change="updateOrderHandle()"
                >
                  <template #suffix>%</template>
                </el-input>
              </div>
              <div class="input_box">
                <span>综合项金额</span>
                <el-input
                  v-if="isRefund"
                  v-model="detailInfo.refundCustomComprehensiveFee"
                  placeholder="请输入"
                  @input="handleInput($event, 'refundCustomComprehensiveFee')"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
                <el-input
                  v-else
                  v-model="detailInfo.customComprehensiveFee"
                  placeholder="请输入"
                  @input="handleInput($event, 'customComprehensiveFee')"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
              </div>
            </div>
            <el-table
              class="order_table"
              border
              :data="detailInfo.itemList"
              style="width: 100%"
              header-cell-class-name="table_head"
              :row-class-name="tableRowClassName"
            >
              <el-table-column v-if="isRefund" type="selection" fixed="left" width="60" />
              <el-table-column prop="mainPicUrl" label="图片" fixed="left" width="120">
                <template #default="{ row }">
                  <span class="change_tag">
                    <img v-if="exchangeTag(row) === 1" class="tag_image" src="@/assets/images/refund.png" />
                    <img v-if="exchangeTag(row) === 2" class="tag_image" src="@/assets/images/exchange.png" />
                    <img v-if="exchangeTag(row) === 3" class="tag_image" src="@/assets/images/supply.png" />
                  </span>
                  <img v-if="row.mainPicUrl" class="row_img" :src="row.mainPicUrl" />
                  <div v-else-if="row.type === 2" class="row_img" style="background: #f3f6f9">
                    <el-icon size="80" color="#E1E6ED"><UserFilled /></el-icon>
                  </div>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称" width="240" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-input
                    v-if="row.type === 3"
                    v-model="row.productName"
                    placeholder="请输入"
                    @change="updateProductHandle(row)"
                  />
                  <span v-else>{{ row.productName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="brandName" label="品牌" width="160">
                <template #default="{ row }">
                  <el-input
                    v-if="row.type === 3"
                    v-model="row.brandName"
                    placeholder="请输入"
                    @change="updateProductHandle(row)"
                  />
                  <span v-else>{{ row.brandName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="modeCode" label="型号" width="160">
                <template #default="{ row }">
                  <el-input
                    v-if="row.type === 3"
                    v-model="row.modeCode"
                    placeholder="请输入"
                    @change="updateProductHandle(row)"
                  />
                  <span v-else>{{ row.modeCode }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="productUnit" label="单位" width="90">
                <template #default="{ row }">
                  {{ row.productUnit || "-" }}
                </template>
              </el-table-column>
              <el-table-column prop="actualUsedNum" :label="isRefund ? '退换数量' : '换补数量'" width="110">
                <template #default="{ row }">
                  <el-input
                    v-model="row.num"
                    oninput="value=value.replace(/^0(0+|\d+)|[^\d]+/g,'');"
                    @change="updateProductHandle(row)"
                  />
                </template>
              </el-table-column>
              <el-table-column v-if="detailInfo.isShowLost" prop="lostRate" label="耗损率" width="90" />
              <el-table-column prop="productUnitPrice" label="材料单价" width="180">
                <template #default="{ row }">
                  <el-input
                    v-if="row.type === 3"
                    placeholder="请输入"
                    v-model="row.mainQuoteMoney"
                    @change="updateProductHandle(row)"
                    style="margin-bottom: 5px"
                  >
                    <template #prefix>主材：</template>
                  </el-input>
                  <el-input
                    v-if="row.type === 3"
                    placeholder="请输入"
                    v-model="row.auxiliaryQuoteMoney"
                    @change="updateProductHandle(row)"
                  >
                    <template #prefix>辅材：</template>
                  </el-input>
                  <span v-else>{{ row.productUnitPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="workerUnitPrice" label="人工费单价" width="180">
                <template #default="{ row }">
                  <el-input
                    v-if="row.type === 3"
                    v-model="row.workerUnitPrice"
                    placeholder="请输入"
                    @change="updateProductHandle(row)"
                  />
                  <span v-else>{{ row.workerUnitPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="unitTotalMoney" label="单项合计" width="130" />
              <el-table-column prop="projectVal" label="预算工程量" width="130" />
              <el-table-column prop="projectTotalMoney" label="汇总合计" width="130" />
              <el-table-column prop="exchangeCause" label="变更原因" min-width="180">
                <template #default="{ row }">
                  <el-input v-model="row.exchangeCause" maxlength="200" @change="updateProductHandle(row)" placeholder="请输入" />
                </template>
              </el-table-column>
              <el-table-column prop="exchangeAmount" label="变更金额" min-width="180">
                <template #default="{ row }">
                  <el-input v-model="row.exchangeAmount" type="number" @change="updateProductHandle(row)" placeholder="请输入" />
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" align="center">
                <template #default="{ row }">
                  <div v-if="isRefund" style="display: grid; gap: 5px; color: #213270">
                    <div>
                      <el-button v-if="row.canExchange" link @click="openSelectProd(row)">替换材料</el-button>
                    </div>
                    <div>
                      <el-button v-if="row.type !== 1 && row.canExchange" link @click="openQuota(row)">替换定额</el-button>
                    </div>
                  </div>
                  <el-button v-else style="color: #ff3333" link @click="openDeleteDialog(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="table_footer mt20" v-if="!isRefund">
              <div class="footer_input">
                <span>成交金额</span>
                <el-input v-model="detailInfo.concludeMoney" type="number" placeholder="请输入" @change="updateOrderHandle()">
                  <template #prefix>￥</template>
                </el-input>
              </div>
              <div class="footer_input" style="flex: 1">
                <span>备注</span>
                <el-input
                  v-model="detailInfo.concludeRemark"
                  :rows="1"
                  autosize
                  maxlength="400"
                  type="textarea"
                  placeholder="请输入"
                  @change="updateOrderHandle()"
                >
                  <template #prefix>￥</template>
                </el-input>
              </div>
            </div>
          </div>
          <!-- v-if="routeAfterSalesType || afterSalesStatus.isChange || afterSalesStatus.isReform || reformId" -->
          <div class="affix">
            <el-affix position="bottom" :offset="21" style="width: 100%" target=".content_table">
              <div class="affix_content">
                <div class="content_btn">
                  <!-- <el-button v-if="reformId" class="btn_exchange" @click="startChangeContract(afterSalesType)">
                    {{ routeAfterSalesType === 1 ? "编辑整改" : "编辑变更" }}
                  </el-button> -->
                  <!-- <template v-else></template> -->
                  <!-- v-if="afterSalesStatus.isChange || routeAfterSalesType === '1'" -->
                  <el-button
                    class="btn_back"
                    v-if="$route.query?.afterSalesType === '1' || !$route.query?.afterSalesType"
                    @click="startChangeContract(1)"
                  >
                    {{ $route.query?.reformId ? "编辑" : "发起" }}整改
                  </el-button>
                  <!-- v-if="afterSalesStatus.isReform || routeAfterSalesType === '3'" -->
                  <el-button
                    class="btn_exchange"
                    v-if="$route.query?.afterSalesType === '3' || !$route.query?.afterSalesType"
                    @click="startChangeContract(3)"
                  >
                    {{ $route.query?.reformId ? "编辑" : "发起" }}增减项
                  </el-button>
                </div>
              </div>
            </el-affix>
          </div>
        </div>
      </div>
    </div>

    <changeContractModal
      v-if="changeContractFlag"
      v-model="changeContractFlag"
      :afterSalesType="afterSalesType"
      :customerId="customerId"
      :contractId="contractId"
      :reformId="reformId"
      :needPayMoney="detailInfo.needPayMoney"
      :grossProfitRate="detailInfo.grossProfitRate"
      :exchangeBudgetId="exchangeInfo.exchangeBudgetId || refundInfo.exchangeBudgetId"
    />

    <selectProduct
      :doSubmit="false"
      :optionInfo="prodOptionInfo"
      @close="closeSelectProDialog()"
      @customSubmit="addMaterialConfirm"
    />

    <quota v-model:isOpen="quotaDialogFlag" :doSubmit="false" :optionInfo="optionInfoQuota" @customSubmit="addQuotaConfirm" />

    <el-dialog v-model="deleteProductFlag" width="400" align-center>
      <div class="delete_dialog">
        <div class="dialog_title mb20">{{ currProduct.productName || "--" }}</div>
        <div class="dialog_content mb50">您正在操作删除此项工程预算，删除后将移除，当前项不会发起退货变更，请谨慎从操作</div>
        <div class="dialog_footer">
          <el-button class="footer_cancel" @click="deleteProductFlag = false">再想想</el-button>
          <el-button class="footer_confirm" @click="deleteProductConfirm()">确认删除</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import searchBox from "@/views/home/components/search";
import changeContractModal from "./components/changeContractModal.vue";
import useCodeArrStore from "@/store/modules/select";
import quota from "./components/quota.vue";
import selectProduct from "./components/selectProduct.vue";
import {
  getExchangeOrder,
  updateReturnOrderInfo,
  updateReplacementOrder,
  updateProductInfo,
  replaceMaterial,
  replaceQuota,
  deleteProduct,
  getPermission
} from "@/apis/quote-price/following";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const goBack = () => router.go(-1);
const budgetId = route.query.budgetId;
const customerId = route.query.customerId;
const contractId = route.query.contractId;
const reformId = route.query.reformId;
const afterSalesType = ref(route.query.afterSalesType);
const routeAfterSalesType = route.query.afterSalesType;
const returnNum = route.query.returnNum;
const replacementNum = route.query.replacementNum;

const orderType = ref(route.query.orderType);
const detailInfo = ref({});
const refundInfo = ref({});
const exchangeInfo = ref({});
const currProduct = ref({});
const prodOptionInfo = ref({});
const optionInfoQuota = ref({});
const loading = ref(false);
const afterSalesStatus = ref({});

const changeContractFlag = ref(false);
const quotaDialogFlag = ref(false);
const deleteProductFlag = ref(false);

const isRefund = computed(() => orderType.value === "1");

const handleInput = (value, key) => {
  const match = value.match(/^\d{0,10}(\.\d{0,2})?/);
  const rawValue = match ? match[0] : "";
  const validValue = rawValue.length <= 8 ? rawValue : rawValue.slice(0, 8);
  detailInfo.value[key] = validValue;
};

const tableRowClassName = ({ rowIndex }) => {
  const num = orderType.value === "1" ? returnNum : replacementNum;
  if (!num) return "";
  if (rowIndex - num < 0) return "";
  return "high-light-row";
};

const exchangeTag = ({ barterType, replenishType }) => {
  let type;
  if (isRefund.value) {
    type = barterType === 1 ? 1 : 2;
  } else {
    type = replenishType === 1 ? 2 : 3;
  }
  return type;
};

const getOrderDetail = async orderType => {
  // loading.value = true;
  const { data } = await getExchangeOrder(budgetId);
  refundInfo.value = data.returnOrder;
  exchangeInfo.value = data.replacementOrder;
  detailInfo.value = {
    ...data,
    ...(orderType === "1" ? refundInfo.value : exchangeInfo.value)
  };
  console.log(detailInfo.value);
  loading.value = false;
};

const startChangeContract = type => {
  changeContractFlag.value = true;
  afterSalesType.value = type;
};

const updateOrderHandle = async () => {
  if (isRefund.value) await updateReturnOrderInfo(detailInfo.value);
  else await updateReplacementOrder(detailInfo.value);
  handleSuccess("修改成功");
};

const updateProductHandle = async item => {
  try {
    await updateProductInfo(item);
    handleSuccess("修改成功");
  } catch (error) {
    handleSuccess();
  }
};

const openSelectProd = item => {
  currProduct.value = item;
  prodOptionInfo.value.type = detailInfo.value.budgetType;
  prodOptionInfo.value.isShow = true;
};

const closeSelectProDialog = () => (prodOptionInfo.value.isShow = false);

const addMaterialConfirm = async skuIds => {
  await replaceMaterial({
    skuIds,
    budgetId,
    id: currProduct.value.id,
    type: currProduct.value.type
  });
  handleSuccess("材料替换成功");
  closeSelectProDialog();
};

const openQuota = item => {
  currProduct.value = item;
  optionInfoQuota.value.budgetId = detailInfo.value.budgetId;
  quotaDialogFlag.value = true;
};

const addQuotaConfirm = async quotaIds => {
  await replaceQuota({
    quotaIds,
    budgetId,
    id: currProduct.value.id,
    type: currProduct.value.type
  });
  handleSuccess("定额替换成功");
  quotaDialogFlag.value = false;
};

const openDeleteDialog = item => {
  currProduct.value = item;
  deleteProductFlag.value = true;
};

const deleteProductConfirm = async () => {
  await deleteProduct({
    exchangeType: orderType.value,
    id: currProduct.value.id,
    type: currProduct.value.type
  });
  handleSuccess("商品删除成功");
  deleteProductFlag.value = false;
};

const getPermissionStatus = async () => {
  const { data } = await getPermission(budgetId);
  afterSalesStatus.value = data;
};

const handleSuccess = message => {
  if (message) ElMessage({ message, type: "success" });
  getOrderDetail(orderType.value);
};

(async () => {
  !afterSalesType.value && (await getPermissionStatus());
  await getOrderDetail(orderType.value);
  if (returnNum && replacementNum) {
    const dom = document.getElementById("tableBox");
    dom.scrollTop = dom.scrollHeight;
  }
})();
</script>

<style lang="scss">
.following_exchange {
  height: calc(100% - 114px);
  margin-top: 114px;
  overflow: hidden;
  .exchange_content {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 20px 15px 15px 20px;
    .content_box {
      height: 100%;
      border-radius: 10px;
      background: white;
      .box_top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 50px;
        padding: 0 20px;
        border-bottom: 1px solid #e1e6ed;
        .top_radio {
          box-shadow: 0px 0px 10px 0px #21327026;
          .radio_btn {
            .el-radio-button__inner {
              width: 160px;
            }
          }
          .is-active {
            .el-radio-button__inner {
              background: #424e66;
              border: 1px solid #424e66;
            }
          }
        }
        .top_btn {
          background: #f2f3f5;
          color: #1d2129;
          border: 0;
          width: 120px;
        }
      }
      .box_content {
        height: calc(100% - 50px);
        overflow: auto;
        .content_table {
          box-sizing: border-box;
          min-height: calc(100% - 70px);
          padding: 20px;
          .el-textarea__inner {
            height: 34px;
            line-height: 24px;
          }
          .row_img {
            display: block;
            width: 80px;
            height: 80px;
            margin: 0 auto;
            border-radius: 4px;
          }
          .table_title {
            line-height: 24px;
            color: #3d3d3d;
            .title_text {
              font-weight: 700;
              font-size: 18px;
            }
            .title_info {
              color: #4e5969;
              .info_price {
                color: #ff3333;
              }
            }
          }
          .table_input {
            display: flex;
            gap: 20px;
            padding: 20px;
            background: #f6f8fa;
            .input_box {
              display: flex;
              align-items: center;
              gap: 10px;
              span {
                white-space: nowrap;
              }
              .el-input__prefix-inner {
                color: black;
                padding-right: 10px;
              }
              .el-input__suffix-inner {
                color: black;
              }
              .el-input__wrapper {
                background: white !important;
              }
            }
          }
          .order_table {
            .el-input__wrapper {
              background: white !important;
            }
          }
          .table_head {
            background: #ebeef1;
          }
          .table_footer {
            display: flex;
            gap: 20px;
            justify-content: space-between;
            .footer_input {
              display: flex;
              align-items: center;
              gap: 10px;
              span {
                white-space: nowrap;
              }
              .el-input__prefix-inner {
                color: black;
                padding-right: 10px;
              }
            }
          }
        }
        .affix {
          .affix_content {
            display: flex;
            justify-content: right;
            align-items: center;
            box-sizing: border-box;
            background: white;
            box-shadow: 0px -5px 10px 0px rgba(66, 78, 102, 0.15);
            padding: 17px;
            .content_btn {
              .btn_back {
                width: 120px;
                height: 36px;
                color: #424e66;
                background: white;
                border: 1px solid #424e66;
                border-radius: 2px;
              }
              .btn_exchange {
                width: 120px;
                height: 36px;
                color: white;
                background: #424e66;
                border: 1px solid #424e66;
                border-radius: 2px;
              }
            }
          }
        }
      }
    }
  }
  .change_tag {
    float: left;
    position: absolute;
    top: 0;
    left: 0;
    .tag_image {
      position: absolute;
    }
  }
  .delete_dialog {
    text-align: center;
    .dialog_title {
      box-sizing: border-box;
      width: 200px;
      font-weight: 700;
      color: #3d3d3d;
      font-size: 18px;
      border: 1px solid #dcdfe6;
      padding: 17px;
      margin: 0 auto;
    }
    .dialog_content {
      color: #3d3d3d;
      line-height: 20px;
    }
    .dialog_footer {
      .footer_cancel,
      .footer_confirm {
        height: 36px;
        width: 120px;
        border: 0;
        border-radius: 2px;
      }
      .footer_cancel {
        background: #f2f3f5;
        color: #1d2129;
      }
      .footer_confirm {
        background: #424e66;
        color: white;
      }
    }
  }
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }
  .el-table .high-light-row {
    --el-table-tr-bg-color: #f5f7fa;
  }
}
</style>
